package org.example.servicepay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.model.manage.bean.Result;
import org.example.servicepay.config.AlipayProperties;
import org.example.servicepay.entity.PayOrder;
import org.example.servicepay.entity.StudentFeeRecord;
import org.example.servicepay.mapper.PayOrderMapper;
import org.example.servicepay.mapper.StudentFeeRecordMapper;
import org.example.servicepay.service.AlipayService;
import org.example.servicepay.vo.AlipayAppOrderResponse;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 支付宝支付服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AlipayServiceImpl implements AlipayService {

    private final AlipayProperties alipayProperties;
    private final PayOrderMapper payOrderMapper;
    private final StudentFeeRecordMapper studentFeeRecordMapper;

    @Override
    public Result<AlipayAppOrderResponse> createAlipayAppOrder(String studentId, Long feeItemId) {
        try {
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

            // 构造请求参数以调用接口
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

            // 设置商户订单号，包含学生ID和缴费项目ID信息
            String outTradeNo = generateOrderNo(studentId, feeItemId);
            model.setOutTradeNo(outTradeNo);

            // 从数据库获取实际的订单金额
            BigDecimal totalAmount = getFeeItemAmount(feeItemId);
            if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error(10041, "获取缴费项目金额失败");
            }
            
            // 设置订单总金额，精确到小数点后两位
            model.setTotalAmount(totalAmount.toString());

            // 设置订单标题，从数据库获取
            String subject = getFeeItemSubject(feeItemId);
            if (subject == null || subject.isEmpty()) {
                subject = "缴费项目";
            }
            model.setSubject(subject);

            // 设置产品代码，APP支付固定为QUICK_MSECURITY_PAY
            model.setProductCode("QUICK_MSECURITY_PAY");
            
            // 设置超时时间
            model.setTimeoutExpress("30m");

            request.setBizModel(model);
            // 设置异步通知地址（如果需要）
            // request.setNotifyUrl("http://your-domain.com/alipay/notify");

            // 执行请求
            String orderStr = alipayClient.sdkExecute(request).getBody();
            
            // 创建响应对象
            AlipayAppOrderResponse response = AlipayAppOrderResponse.of(outTradeNo, orderStr);
            
            log.info("支付宝订单创建成功，订单号：{}，订单字符串：{}", outTradeNo, orderStr);
            return Result.success(response);
        } catch (AlipayApiException e) {
            log.error("创建支付宝订单失败：{}", e.getMessage(), e);
            return Result.error(10035, "创建支付宝订单失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("创建支付宝订单异常：{}", e.getMessage(), e);
            return Result.error(10036, "创建支付宝订单异常：" + e.getMessage());
        }
    }
    
    @Override
    public Result<String> queryAlipayOrderStatus(String outTradeNo, String tradeNo) {
        try {
            // 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

            // 构造请求参数以调用接口
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();

            // 设置订单支付时传入的商户订单号
            if (outTradeNo != null && !outTradeNo.isEmpty()) {
                model.setOutTradeNo(outTradeNo);
            }

            // 设置支付宝交易号
            if (tradeNo != null && !tradeNo.isEmpty()) {
                model.setTradeNo(tradeNo);
            }

            // 设置查询选项
            List<String> queryOptions = new ArrayList<String>();
            queryOptions.add("trade_settle_info");
            model.setQueryOptions(queryOptions);

            request.setBizModel(model);

            // 执行请求
            String response = alipayClient.execute(request).getBody();
            
            log.info("支付宝订单查询成功，响应内容：{}", response);
            
            // 解析支付宝返回的响应数据
            JSONObject jsonResponse = JSONObject.parseObject(response);
            JSONObject alipayTradeQueryResponse = jsonResponse.getJSONObject("alipay_trade_query_response");
            
            if (alipayTradeQueryResponse != null) {
                String code = alipayTradeQueryResponse.getString("code");
                // 判断查询是否成功
                if ("10000".equals(code)) {
                    String tradeStatus = alipayTradeQueryResponse.getString("trade_status");
                    // 判断订单是否支付成功
                    if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                        // 订单支付成功，更新数据库中对应的记录
                        updateStudentPayStatus(outTradeNo);
                        return Result.success("订单支付成功");
                    } else {
                        return Result.success("订单状态：" + tradeStatus);
                    }
                } else {
                    String msg = alipayTradeQueryResponse.getString("msg");
                    return Result.error(10037, "查询支付宝订单失败：" + msg);
                }
            } else {
                return Result.error(10037, "解析支付宝响应失败");
            }
        } catch (AlipayApiException e) {
            log.error("查询支付宝订单失败：{}", e.getMessage(), e);
            return Result.error(10037, "查询支付宝订单失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("查询支付宝订单异常：{}", e.getMessage(), e);
            return Result.error(10038, "查询支付宝订单异常：" + e.getMessage());
        }
    }

    /**
     * 获取缴费项目金额
     * @param feeItemId 缴费项目ID
     * @return 金额
     */
    private BigDecimal getFeeItemAmount(Long feeItemId) {
        try {
            PayOrder payOrder = payOrderMapper.selectById(feeItemId);
            if (payOrder != null) {
                // 数据库中amount字段是分为单位，需要转换为元
                return new BigDecimal(payOrder.getAmount()).divide(new BigDecimal("100"));
            }
        } catch (Exception e) {
            log.error("获取缴费项目金额异常：{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取缴费项目标题
     * @param feeItemId 缴费项目ID
     * @return 标题
     */
    private String getFeeItemSubject(Long feeItemId) {
        try {
            PayOrder payOrder = payOrderMapper.selectById(feeItemId);
            if (payOrder != null) {
                return payOrder.getSubject();
            }
        } catch (Exception e) {
            log.error("获取缴费项目标题异常：{}", e.getMessage(), e);
        }
        return "缴费项目";
    }

    /**
     * 更新学生缴费状态
     * @param outTradeNo 商户订单号
     */
    private void updateStudentPayStatus(String outTradeNo) {
        try {
            // 根据商户订单号解析学生ID和缴费项目ID
            // 商户订单号格式为：ALIPAY_{学生ID}_{缴费项目ID}_{时间戳}
            String[] parts = outTradeNo.split("_");
            if (parts.length >= 4) {
                String studentId = parts[1];
                Long payId = Long.parseLong(parts[2]);
                
                // 更新学生缴费记录状态
                int updatedRows = studentFeeRecordMapper.updateFeeStatus(studentId, payId, 1);
                if (updatedRows > 0) {
                    log.info("学生缴费记录更新成功，学生ID：{}，缴费项目ID：{}", studentId, payId);
                } else {
                    log.warn("未找到对应的学生缴费记录，学生ID：{}，缴费项目ID：{}", studentId, payId);
                }
            }
        } catch (Exception e) {
            log.error("更新学生缴费状态异常：{}", e.getMessage(), e);
        }
    }

    /**
     * 获取支付宝配置
     * @return AlipayConfig
     */
    private AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(alipayProperties.getGatewayUrl());
        alipayConfig.setAppId(alipayProperties.getAppId());
        alipayConfig.setPrivateKey(alipayProperties.getPrivateKey());
        alipayConfig.setFormat(alipayProperties.getFormat());
        alipayConfig.setAlipayPublicKey(alipayProperties.getAlipayPublicKey());
        alipayConfig.setCharset(alipayProperties.getCharset());
        alipayConfig.setSignType(alipayProperties.getSignType());
        System.out.println("alipayConfig = " + alipayConfig.toString());
        return alipayConfig;
    }

    /**
     * 生成订单号
     * @param studentId 学生ID
     * @param feeItemId 缴费项目ID
     * @return 订单号
     */
    private String generateOrderNo(String studentId, Long feeItemId) {
        // 订单号格式：ALIPAY_{学生ID}_{缴费项目ID}_{时间戳}
        return "ALIPAY_" + studentId + "_" + feeItemId + "_" + System.currentTimeMillis();
    }
}